<template>
  <div class="localstorage-hook-demo p-4">
    <div class="space-y-6">
      <!-- 基础字符串存储 -->
      <div class="storage-section">
        <h4 class="storage-title">字符串存储</h4>
        <div class="space-y-3">
          <div class="flex items-center space-x-3">
            <label class="text-sm font-medium w-20">姓名:</label>
            <input v-model="name" class="input-field flex-1" placeholder="输入您的姓名" />
            <button @click="clearName" class="btn-clear">清空</button>
          </div>
          <div class="storage-info">
            <div class="info-label">存储值:</div>
            <div class="info-value">{{ name || '(空)' }}</div>
          </div>
          <div class="text-xs text-gray-500">💡 刷新页面数据依然保存，打开新标签页查看同步效果</div>
        </div>
      </div>

      <!-- 对象存储 -->
      <div class="storage-section">
        <h4 class="storage-title">对象存储 (用户配置)</h4>
        <div class="space-y-3">
          <div class="grid grid-cols-2 gap-3">
            <div>
              <label class="block text-sm font-medium mb-1">用户名:</label>
              <input v-model="userConfig.username" class="input-field w-full" />
            </div>
            <div>
              <label class="block text-sm font-medium mb-1">邮箱:</label>
              <input v-model="userConfig.email" type="email" class="input-field w-full" />
            </div>
          </div>

          <div class="grid grid-cols-2 gap-3">
            <div>
              <label class="block text-sm font-medium mb-1">主题:</label>
              <select v-model="userConfig.theme" class="select-field w-full">
                <option value="light">浅色</option>
                <option value="dark">深色</option>
                <option value="auto">自动</option>
              </select>
            </div>
            <div>
              <label class="block text-sm font-medium mb-1">语言:</label>
              <select v-model="userConfig.language" class="select-field w-full">
                <option value="zh">中文</option>
                <option value="en">English</option>
                <option value="ja">日本語</option>
              </select>
            </div>
          </div>

          <div class="flex items-center space-x-4">
            <label class="flex items-center space-x-2">
              <input v-model="userConfig.notifications" type="checkbox" class="checkbox-field" />
              <span class="text-sm">开启通知</span>
            </label>
            <label class="flex items-center space-x-2">
              <input v-model="userConfig.darkMode" type="checkbox" class="checkbox-field" />
              <span class="text-sm">深色模式</span>
            </label>
          </div>

          <div class="storage-preview">
            <div class="info-label">存储的配置对象:</div>
            <pre class="info-json">{{ JSON.stringify(userConfig, null, 2) }}</pre>
          </div>

          <button @click="resetUserConfig" class="btn-reset">重置配置</button>
        </div>
      </div>

      <!-- 数组存储 -->
      <div class="storage-section">
        <h4 class="storage-title">数组存储 (收藏列表)</h4>
        <div class="space-y-3">
          <div class="flex space-x-3">
            <input
              v-model="newFavorite"
              @keyup.enter="addFavorite"
              class="input-field flex-1"
              placeholder="添加收藏项目"
            />
            <button @click="addFavorite" :disabled="!newFavorite.trim()" class="btn-add">
              添加
            </button>
          </div>

          <div class="favorites-list">
            <div v-for="(item, index) in favorites" :key="index" class="favorite-item">
              <span class="favorite-text">{{ item }}</span>
              <button @click="removeFavorite(index)" class="btn-remove">删除</button>
            </div>
            <div v-if="favorites.length === 0" class="empty-state">暂无收藏项目</div>
          </div>

          <div class="flex space-x-2">
            <button @click="clearFavorites" :disabled="favorites.length === 0" class="btn-clear">
              清空收藏
            </button>
            <button @click="addSampleFavorites" class="btn-sample">添加示例数据</button>
          </div>
        </div>
      </div>

      <!-- 自定义序列化 -->
      <div class="storage-section">
        <h4 class="storage-title">自定义序列化 (日期存储)</h4>
        <div class="space-y-3">
          <div class="flex items-center space-x-3">
            <label class="text-sm font-medium">选择日期:</label>
            <input v-model="dateString" type="date" class="input-field" />
            <button @click="setToday" class="btn-today">设为今天</button>
          </div>

          <div class="storage-info">
            <div class="info-label">存储的日期对象:</div>
            <div class="info-value">
              {{ selectedDate ? selectedDate.toLocaleString() : '(未选择)' }}
            </div>
          </div>

          <div class="storage-info">
            <div class="info-label">原始存储值:</div>
            <div class="info-value font-mono text-xs">
              {{ rawStorageValue || '(空)' }}
            </div>
          </div>

          <button @click="clearDate" class="btn-clear">清空日期</button>
        </div>
      </div>
    </div>

    <!-- Hook 说明 -->
    <div class="mt-6 p-4 bg-blue-50 border border-blue-200 rounded">
      <h5 class="text-sm font-medium text-blue-800 mb-2">💾 useLocalStorage Hook 特性</h5>
      <ul class="text-xs text-blue-700 space-y-1">
        <li>• <strong>自动同步</strong>: 数据变化时自动保存到 localStorage</li>
        <li>• <strong>类型安全</strong>: 支持任意类型的数据存储</li>
        <li>• <strong>跨标签页同步</strong>: 监听 storage 事件，多标签页数据同步</li>
        <li>• <strong>自定义序列化</strong>: 可自定义数据的序列化和反序列化方式</li>
        <li>• <strong>错误处理</strong>: 内置错误处理，避免存储失败导致崩溃</li>
        <li>• <strong>响应式</strong>: 返回响应式引用，UI 自动更新</li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useLocalStorage } from '@/hooks/useLocalStorage'

// 基础字符串存储
const [name, setName, clearName] = useLocalStorage('demo-name', '')

// 对象存储
interface UserConfig {
  username: string
  email: string
  theme: 'light' | 'dark' | 'auto'
  language: 'zh' | 'en' | 'ja'
  notifications: boolean
  darkMode: boolean
}

const defaultUserConfig: UserConfig = {
  username: '',
  email: '',
  theme: 'light',
  language: 'zh',
  notifications: true,
  darkMode: false,
}

const [userConfig, setUserConfig] = useLocalStorage('demo-user-config', defaultUserConfig)

const resetUserConfig = () => {
  setUserConfig({ ...defaultUserConfig })
}

// 数组存储
const [favorites, setFavorites] = useLocalStorage<string[]>('demo-favorites', [])
const newFavorite = ref('')

const addFavorite = () => {
  if (newFavorite.value.trim()) {
    setFavorites([...favorites.value, newFavorite.value.trim()])
    newFavorite.value = ''
  }
}

const removeFavorite = (index: number) => {
  const newFavorites = [...favorites.value]
  newFavorites.splice(index, 1)
  setFavorites(newFavorites)
}

const clearFavorites = () => {
  setFavorites([])
}

const addSampleFavorites = () => {
  const samples = ['Vue.js', 'React', 'Angular', 'TypeScript', 'Vite']
  setFavorites([...favorites.value, ...samples.filter((item) => !favorites.value.includes(item))])
}

// 自定义序列化（日期）
const [selectedDate, setSelectedDate, clearDate] = useLocalStorage<Date | null>(
  'demo-selected-date',
  null,
  {
    serializer: {
      read: (value: string) => (value ? new Date(value) : null),
      write: (value: Date | null) => (value ? value.toISOString() : ''),
    },
  },
)

const dateString = computed({
  get: () => (selectedDate.value ? selectedDate.value.toISOString().split('T')[0] : ''),
  set: (value: string) => {
    setSelectedDate(value ? new Date(value) : null)
  },
})

const setToday = () => {
  setSelectedDate(new Date())
}

const rawStorageValue = computed(() => {
  try {
    return window.localStorage.getItem('demo-selected-date')
  } catch {
    return null
  }
})
</script>

<style scoped lang="scss">
.localstorage-hook-demo {
  @apply bg-gray-50;
}

.storage-section {
  @apply p-4 bg-white rounded-lg border border-gray-200;
}

.storage-title {
  @apply text-base font-semibold text-gray-800 mb-4 pb-2 border-b border-gray-200;
}

.input-field,
.select-field {
  @apply px-3 py-2 text-sm border border-gray-300 rounded focus:ring-2 focus:ring-blue-500 focus:border-transparent;
}

.checkbox-field {
  @apply rounded border-gray-300 text-blue-600 focus:ring-blue-500;
}

.btn-clear,
.btn-reset,
.btn-add,
.btn-remove,
.btn-today,
.btn-sample {
  @apply px-3 py-2 text-sm rounded font-medium transition-colors;
}

.btn-clear {
  @apply bg-gray-500 text-white hover:bg-gray-600;
}

.btn-reset {
  @apply bg-orange-500 text-white hover:bg-orange-600;
}

.btn-add {
  @apply bg-green-500 text-white hover:bg-green-600 disabled:opacity-50 disabled:cursor-not-allowed;
}

.btn-remove {
  @apply bg-red-500 text-white hover:bg-red-600 text-xs px-2 py-1;
}

.btn-today {
  @apply bg-blue-500 text-white hover:bg-blue-600;
}

.btn-sample {
  @apply bg-purple-500 text-white hover:bg-purple-600;
}

.storage-info {
  @apply p-3 bg-gray-100 rounded;
}

.storage-preview {
  @apply p-3 bg-gray-100 rounded;
}

.info-label {
  @apply text-sm font-medium text-gray-700 mb-1;
}

.info-value {
  @apply text-sm text-gray-800;
}

.info-json {
  @apply text-xs font-mono text-gray-800 whitespace-pre-wrap;
}

.favorites-list {
  @apply space-y-2 max-h-40 overflow-y-auto;
}

.favorite-item {
  @apply flex items-center justify-between p-2 bg-gray-50 rounded border;
}

.favorite-text {
  @apply text-sm text-gray-800 flex-1;
}

.empty-state {
  @apply text-center text-gray-400 text-sm py-4;
}
</style>
